package com.liangdemo.web.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 实现Callable创建线程
 * 可以有返回值,并且抛出异常
 */
public class CallableDemo1 implements Callable {
    @Override
    public Object call() throws Exception {
        int a = 10;
        int b = 100;
        return a + b;
    }

    public static void main(String[] args) {
        //创建实现类对象
        CallableDemo1 c1 = new CallableDemo1();

        //将创建的实现类对象,传递给FutureTask构造器,并创建FutureTask对象
        FutureTask<Integer> integerFutureTask = new FutureTask<>(c1);

        //将FutureTask对象作为参数传递给Thread类，Thread类对象调用start()方法启动线程：此处的参数为Runnable类型，
        //FutureTask同时实现了Runnable,Future接口，所以FutureTask对象就可以作为此处的参数
        new Thread(integerFutureTask, "线程1").start();

        try {
            //调用get()方法获取call()方法的返回值
            Integer sum = integerFutureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

    }
}
